import React, { useState, useEffect } from 'react';
import { useRemediation } from '@/contexts/RemediationContext';
import { showMessage } from '@/components/common/MessageTip';
import LeftPanel from '@/components/Remediation/LeftPanel';
import RightPanel from '@/components/Remediation/RightPanel';
import RemediationForm from '@/components/Remediation/RemediationForm';
import { type RemediationFormData } from '@/types/Remediation';

// 模态框组件
interface ModalProps {
  isOpen: boolean;
  onClose: () => void;
  children: React.ReactNode;
}

const Modal: React.FC<ModalProps> = ({ isOpen, onClose, children }) => {
  if (!isOpen) return null;
  
  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-background rounded-lg shadow-lg max-w-2xl w-full max-h-[90vh] overflow-y-auto">
        <div className="absolute top-4 right-4">
          <button
            onClick={onClose}
            className="p-1 hover:bg-muted rounded-full transition-colors"
          >
            <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        {children}
      </div>
    </div>
  );
};

/**
 * 整改台账页面组件
 */
const RemediationView: React.FC = () => {
  const { addRemediationItem } = useRemediation();
  const [isFormModalOpen, setIsFormModalOpen] = useState(false);
  const [formData, setFormData] = useState<RemediationFormData | null>(null);
  
  // 处理从检查项创建整改项
  const handleCreateFromComplianceItem = (data: RemediationFormData) => {
    setFormData(data);
    setIsFormModalOpen(true);
  };
  
  // 处理表单提交
  const handleFormSubmit = async (data: RemediationFormData) => {
    try {
      const newItem = await addRemediationItem(data);
      console.log('newItem', newItem);
      if (newItem) {
        showMessage('success', '整改项创建成功');
        setIsFormModalOpen(false);
      } else {
        showMessage('warning', '整改项创建未完成，请重试');
      }
    } catch (error) {
      showMessage('error', `整改项创建失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  };
  
  // 处理错误状态
  const { error } = useRemediation();
  
  useEffect(() => {
    if (error) {
      showMessage('error', `操作失败: ${error.message}`);
    }
  }, [error]);

  return (
    <>
      <div className="min-h-screen flex flex-col md:flex-row overflow-hidden">
        {/* 左侧面板 - 待整改检查项 */}
        <div className="w-full md:w-1/3 border-r overflow-y-auto max-h-screen md:max-h-none">
          <LeftPanel onCreateRemediation={handleCreateFromComplianceItem} />
        </div>
        
        {/* 右侧面板 - 整改台账管理 */}
        <div className="w-full md:w-2/3 overflow-y-auto max-h-screen md:max-h-none">
          <RightPanel />
        </div>
      </div>
      
      {/* 从检查项创建整改项的表单模态框 */}
      <Modal
        isOpen={isFormModalOpen}
        onClose={() => setIsFormModalOpen(false)}
      >
        <RemediationForm
          initialData={formData || undefined}
          onSubmit={handleFormSubmit}
          onCancel={() => setIsFormModalOpen(false)}
          title="确认创建整改项"
          submitText="确认创建"
          isFromComplianceItem={true}
        />
      </Modal>
    </>
  );
};

export default RemediationView;
